<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Corp\Action\Dashboard;

use Exception;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 企业微信授权- 设置接受事件服务器.
 *
 * Class ContactSecretStore.
 * @Controller
 */
class CallbackSet extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/dashboard/corp/callbackSet", methods="POST")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array|
     * @throws Exception 异常处理
     */
    public function handle()
    {
        # # 接收参数
        $params['corpId'] = $this->request->input('corpId');
        $params['token'] = $this->request->input('token');
        $params['encodingAesKey'] = $this->request->input('encodingAesKey');
        $this->validated($params, 'store');
        # # 数据操作
        Db::beginTransaction();
        try {
            # # 企业授信
            $this->corpService->updateCorpById($params['corpId'], ['token' => $params['token'], 'encoding_aes_key' => $params['encodingAesKey']]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '接收事件服务器创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '接收事件服务器创建失败');
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'corpId' => 'required | integer | min:0 | bail',
            'token' => 'required | string | bail',
            'encodingAesKey' => 'required | string | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'corpId.required' => '企业ID 必填',
            'corpId.integer' => '企业ID 必须为整型',
            'token.required' => 'token 必填',
            'encodingAesKey.required' => 'encodingAesKey 必填',
        ];
    }
}
